import React, {Component} from 'react';
import {Card, Alert, Typography, DatePicker, Table, Button, Row} from 'antd';
import {connect} from 'dva';
import * as echart from 'echarts';
import {addResizeHook} from '@/utils/resize';
import {trigger} from "@/utils/utils";
import moment from "moment";
import time, {convertDateFromString, currentTime, dateFormat} from "@/utils/time";
import {getLatestTime} from "@/services/indicator";

const {RangePicker} = DatePicker;

// 通用的图表
class Common extends Component {
  stopLoop = false;

  state = {
  };

  async componentDidMount() {
    const {name, dispatch, stopLoop,timeRange=1} = this.props;

    const resp = await getLatestTime({
      itemName: name,
    });
    const {start,end,current} = resp.detail
    let startTime = convertDateFromString(start)
    let endTime = convertDateFromString(end)
    let currentTime = convertDateFromString(current)

    this.stopLoop = stopLoop;
    // const selectedStartTime = time.minusDay(time.getStartOfDay(),timeRange)
    const selectedStartTime = time.minusDay(startTime,1)
    const selectedEndTime = endTime

    this.tableRef = requestAnimationFrame(() =>
      trigger(
        () => {
          dispatch({
            type: 'indicator/chart',
            payload: {
              name,
              start: dateFormat(selectedStartTime),
              end: dateFormat(selectedEndTime)
            },
          });
        },
        new Date().valueOf(),
        200000,
        true,
        () => false,
      ),
    );

    this.setState({selectedStartTime,selectedEndTime});


  }

  componentWillUnmount() {
    cancelAnimationFrame(this.tableRef);
    this.stopLoop = true;
  }

  downloadHistory = () => {
    const {selectedStartTime, selectedEndTime} = this.state;
    const {name} = this.props;
    const payload = {
      name,
      start: dateFormat(selectedStartTime),
      end: dateFormat(selectedEndTime)
    };
    const fileName = `${dateFormat(selectedStartTime)  }至${  dateFormat(selectedEndTime)  }数据.xlsx`;
    this.props.dispatch({
      type: 'indicator/downloadHistory',
      payload,
      callback: blob => {
        // 回调触发文件下载
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, fileName);
        } else {
          const link = document.createElement('a');
          const evt = document.createEvent('MouseEvents');
          link.style.display = 'none';
          link.href = window.URL.createObjectURL(blob);
          link.download = fileName;
          document.body.appendChild(link); // 此写法兼容可火狐浏览器
          evt.initEvent('click', false, false);
          link.dispatchEvent(evt);
          document.body.removeChild(link);
        }
      }
    });
  };


  timePick = value => {
    this.state.selectedStartTime = value[0].toDate();
    this.state.selectedEndTime = value[1].toDate();
    const {name, dispatch} = this.props
    dispatch({
      type: 'indicator/chart',
      payload: {
        name,
        start: dateFormat(value[0].toDate()),
        end: dateFormat(value[1].toDate())
      },
    });
  };

  render() {
    const dtFormat = 'YYYY-MM-DD HH';
    const {selectedStartTime,selectedEndTime} = this.state

    const {indicator, name,title,scroll} = this.props;
    const tablaData = indicator[name];
    /*
    [
      {title: '区域', dataIndex: 'area', key: 'area'},
      {title: '周向均匀性', dataIndex: 'zhou', key: 'zhou'},
      {title: '高度', dataIndex: 'height', key: 'height'},
      {title: '径向均匀性', dataIndex: 'jing', key: 'jing'},
    ]
     */

    return (
      <Card title={title}>
        <Row>
        <RangePicker
          key={Math.random()} //强制刷新组件
          style={{width: 300}}
          showTime={{format: 'HH'}}
          format={dtFormat}
          placeholder={['开始时间', '结束时间']}
          onOk={this.timePick}
          defaultValue={[moment(selectedStartTime, dtFormat), moment(selectedEndTime, dtFormat)]}
        />

        <Button style={{float: 'right'}} type="default" shape="round" size='small'
                onClick={this.downloadHistory}>下载</Button>

        </Row>

        <Row>
        {tablaData && <Table
          size="small"
          columns={tablaData.columns}
          dataSource={tablaData.data}
          pagination={false}
          scroll={scroll}
        />
        }
        </Row>
      </Card>
    );
  }
}

export default connect(({indicator, global}) => ({
  indicator,
  global,
}))(Common);
